package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1.计算时间。
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String join = StringUtils.join(dateList,",");

        //2.计算每天的营业额
        List<Double> doubleList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnoverStatistics =  orderMapper.getTurnoverStatistics(map);
            turnoverStatistics = turnoverStatistics == null ? 0.0 : turnoverStatistics;
            doubleList.add(turnoverStatistics);
        }
        String join1 = StringUtils.join(doubleList,",");

        TurnoverReportVO build = TurnoverReportVO.builder()
                .dateList(join)
                .turnoverList(join1)
                .build();


        return build;
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1.获取动态时间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String join = StringUtils.join(dateList,",");

        //2.获取每天的用户数量
        //新用户
        List<Integer> newUserReport = new ArrayList<>();
        //总共的用户
        List<Integer> totalUserReport = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime" ,beginTime);
            Integer totalUser = userMapper.getUserStatistics(map);
            totalUserReport.add(totalUser);
            map.put("endTime", endTime);
            Integer newUser = userMapper.getUserStatistics(map);
            newUserReport.add(newUser);

        }
        String join1 = StringUtils.join(newUserReport,",");
        String join2 = StringUtils.join(totalUserReport,",");

        UserReportVO build = UserReportVO.builder()
                .dateList(join)
                .newUserList(join1)
                .totalUserList(join2)
                .build();


        return build;
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //1.获取动态时间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String join = StringUtils.join(dateList,",");

        //2.每日订单数
        List<Integer> totalOrder = new ArrayList<>();
        //每日有效订单数
        List<Integer> validOrder = new ArrayList<>();

//        //订单总数
//        Integer totalOrderCount = 0;
//        //有效订单数
//        Integer validOrderCount = 0;
//        //订单完成率
//        Double orderCompletionRate;

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            //每日订单数
            Integer total = orderMapper.getOrdersStatistics(map);
            totalOrder.add(total);
            //totalOrderCount += total;

            //每日有效订单数
            map.put("status", Orders.COMPLETED);//已完成
            Integer valid = orderMapper.getOrdersStatistics(map);
            validOrder.add(valid);
            //validOrderCount += valid;
        }
        String s = StringUtils.join(totalOrder,",");
        String s1 = StringUtils.join(validOrder,",");

        //订单总数(通过stream流遍历集合里面的所有元素）
        Integer totalOrderCount = totalOrder.stream().reduce(Integer::sum).get();
        //有效订单数
        Integer validOrderCount = validOrder.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = totalOrderCount == 0 ? 0.0 : validOrderCount.doubleValue() / totalOrderCount;
//        Double orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;


        //orderCompletionRate = Double.valueOf(validOrderCount / totalOrderCount);

        OrderReportVO build = OrderReportVO.builder()
                .dateList(join)
                .orderCountList(s)
                .validOrderCountList(s1)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return build;
    }


    /**
     * 查询销量排名top10接口
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

            List<GoodsSalesDTO> salesDTOS = orderMapper.getTop10(beginTime,endTime);
        List<String> nameList = salesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String join = StringUtils.join(nameList, ",");

        List<Integer> numbers = salesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String join1 = StringUtils.join(numbers, ",");


        return SalesTop10ReportVO.builder().nameList(join).numberList(join1).build();
    }

    /**
     * 导出数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime date1 = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime date2 = LocalDateTime.of(dateEnd, LocalTime.MAX);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(date1, date2);


        //2.通过POI将数据写到excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //填充第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //填充第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for(int i = 0; i < 30; i++){
                LocalDate date = dateBegin.plusDays(i);
                LocalDateTime d1 = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime d2 = LocalDateTime.of(date, LocalTime.MAX);
                //获取某一天的营业额
                BusinessDataVO businessData = workspaceService.getBusinessData(d1, d2);

                //获取某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());



            }




            //3.通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }






    }

}
